package com.dayaokeji.rhythmschoolstudent.client.home;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ad.AdCallback;
import com.dayaokeji.rhythmschoolstudent.client.common.ad.bean.FileInfoWrapper;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseFragment;
import com.dayaokeji.rhythmschoolstudent.client.home.adapter.BannerAdapter;
import com.dayaokeji.rhythmschoolstudent.client.home.course.CourseDetailActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.course.CourseTableActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.data.bean.HomeNewBean;
import com.dayaokeji.rhythmschoolstudent.client.home.data.bean.HomeNewType;
import com.dayaokeji.rhythmschoolstudent.client.home.meeting.MeetingActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.meeting.MeetingDetailActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.utils.HomeNewTopTimeFilterHelper;
import com.dayaokeji.rhythmschoolstudent.client.main.MainFragment;
import com.dayaokeji.rhythmschoolstudent.client.mine.bulletin.BulletinActivity;
import com.dayaokeji.rhythmschoolstudent.event.BulletinEvent;
import com.dayaokeji.rhythmschoolstudent.event.ReqNewCourseEvent;
import com.dayaokeji.rhythmschoolstudent.utils.DateUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.Page;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.BulletinApi;
import com.dayaokeji.server_api.api.CourseApi;
import com.dayaokeji.server_api.api.MeetingApi;
import com.dayaokeji.server_api.api.ResourceApi;
import com.dayaokeji.server_api.domain.Bulletin;
import com.dayaokeji.server_api.domain.Course;
import com.dayaokeji.server_api.domain.FileInfo;
import com.dayaokeji.server_api.domain.Meeting;
import com.dayaokeji.server_api.domain.UserInfo;
import com.dayaokeji.server_api.utils.FileFunctionFlag;
import com.orhanobut.logger.Logger;
import com.paradoxie.autoscrolltextview.VerticalTextview;
import com.qq.e.ads.nativ.NativeExpressADView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;

/**
 * home
 */
public class HomeFragment extends BaseFragment implements MainFragment{


    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @BindView(R.id.fl_new_meeting)
    FrameLayout flNewMeeting;
    @BindView(R.id.vt1)
    VerticalTextview vt1;
    @BindView(R.id.vt2)
    VerticalTextview vt2;
    @BindView(R.id.ll_notice)
    LinearLayout llNotice;
    @BindView(R.id.tv_home_new_title)
    TextView tvHomeNewTitle;
    @BindView(R.id.ll_top_new)
    LinearLayout llTopNew;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;

    private List<Bulletin> bulletinList;

    private MeetingApi meetingApi = ApiUtils.getApi(MeetingApi.class);
    private CourseApi courseApi = ApiUtils.getApi(CourseApi.class);
    private ResourceApi resourceApi = ApiUtils.getApi(ResourceApi.class);
    private BulletinApi bulletinApi = ApiUtils.getApi(BulletinApi.class);
    private Call<ServerResponse<Page<Meeting>>> userTodayMeetingList;
    private Call<ServerResponse<List<FileInfo>>> selectSlideCall;
    private Call<ServerResponse<Page<Bulletin>>> messagesCall;
    private List<FileInfo> fileInfos;
    private Call<ServerResponse<Page<Course>>> newCourseListCall;
    private Call<ServerResponse<Page<Course>>> courseByIdCall;
    private Call<ServerResponse<Page<Meeting>>> findMeetingByIdCall;

    private static final int REQ_NEW_COURSE_MEETING_INTERVAL = 1;
    private Disposable courseSubscribe;
    private Disposable meetingSubscribe;
    private View meetingView;
    private BannerAdapter bannerAdapter;

    @Nullable
    @Override
    protected View onCreate(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container,false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }

    private void init() {
        setupView();
        setOnListener();
        loadSlide();
        reqNewCourse();
        loadBulletin();
    }

    private void setupView() {
        vt1.setTextStillTime(5000);//设置停留时长间隔
        vt2.setTextStillTime(5000);//设置停留时长间隔
        vt1.setAnimTime(300);//设置进入和退出的时间间隔
        vt2.setAnimTime(300);//设置进入和退出的时间间隔
    }

    private void setOnListener() {
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadSlide();
                reqNewCourse();
                loadBulletin();
            }
        });
    }

    private void reqNewCourse() {
        UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            String id = userInfo.getId();
            newCourseListCall = courseApi.newCourseList(id, 1, DateUtils.format(DateUtils.getDayBegin(), DateUtils.FORMAT_DATETIME), userInfo.getUniversityId(), 1, 10000);
            newCourseListCall.enqueue(new ServerCallback<Page<Course>>() {
                @Override
                public void onResponse(boolean success, final ServerResponse<Page<Course>> response) {
                    if (refreshLayout != null && refreshLayout.isRefreshing()) {
                        refreshLayout.setRefreshing(false);
                    }
                    if (success) {
                        if (response.getBody() != null && response.getBody().getList() != null && !response.getBody().getList().isEmpty()) {
                            Course course = HomeNewTopTimeFilterHelper.INSTANCE.courseTimeFilter(response.getBody().getList());
                            if (course != null) {
                                HomeNewBean homeNewBean = new HomeNewBean(course.getCourseDetailId(),HomeNewType.COURSE, course.getName(), course.getActStartTime(), course.getRoomName());
                                createNewView(homeNewBean);
                                if (courseSubscribe != null) {
                                    courseSubscribe.dispose();
                                }
                                courseSubscribe = Observable.interval(REQ_NEW_COURSE_MEETING_INTERVAL, TimeUnit.MINUTES).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
                                    @Override
                                    public void accept(Long aLong) throws Exception {
                                        Course course = HomeNewTopTimeFilterHelper.INSTANCE.courseTimeFilter(response.getBody().getList());
                                        if (course != null) {
                                            HomeNewBean homeNewBean = new HomeNewBean(course.getCourseDetailId(), HomeNewType.COURSE, course.getName(), course.getActStartTime(), course.getRoomName());
                                            createNewView(homeNewBean);
                                        }
                                    }
                                });

                            }else {
                                reqNewMeeting();
                            }
                        }else{
                            reqNewMeeting();
                        }
                    }else {
                        reqNewMeeting();
                    }
                }
                @Override
                public void onFailure(Call<ServerResponse<Page<Course>>> call, Throwable t) {
                    super.onFailure(call, t);
                    if (refreshLayout != null && refreshLayout.isRefreshing()) {
                        refreshLayout.setRefreshing(false);
                    }
                    reqNewMeeting();
                }
            });
        }
    }

    /**
     * 获取最新会议数据
     */
    private void reqNewMeeting() {
        UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            String id = userInfo.getId();
            userTodayMeetingList = meetingApi.userTodayList(1, id, DateUtils.format(DateUtils.getDayBegin(), DateUtils.FORMAT_DATETIME), 10000);
            userTodayMeetingList.enqueue(new ServerCallback<Page<Meeting>>() {
                @Override
                public void onResponse(boolean success, final ServerResponse<Page<Meeting>> response) {
                    if (refreshLayout != null && refreshLayout.isRefreshing()) {
                        refreshLayout.setRefreshing(false);
                    }
                    if (success) {
                        if (response.getBody() != null && response.getBody().getList() != null && !response.getBody().getList().isEmpty()) {
                            Meeting meeting = HomeNewTopTimeFilterHelper.INSTANCE.meetingTimeFilter(response.getBody().getList());
                            Logger.d("isVisible === "+isVisible());
                            if (meeting != null) {
                                HomeNewBean homeNewBean = new HomeNewBean(meeting.getDetailId(),HomeNewType.MEETING, meeting.getName(), meeting.getActStartTime(), meeting.getRoomName());
                                createNewView(homeNewBean);
                                if (meetingSubscribe != null) {
                                    meetingSubscribe.dispose();
                                }
                                meetingSubscribe = Observable.interval(REQ_NEW_COURSE_MEETING_INTERVAL, TimeUnit.MINUTES).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
                                    @Override
                                    public void accept(Long aLong) throws Exception {
                                        Meeting meeting = HomeNewTopTimeFilterHelper.INSTANCE.meetingTimeFilter(response.getBody().getList());
                                        if (meeting != null) {
                                            HomeNewBean homeNewBean = new HomeNewBean(meeting.getDetailId(), HomeNewType.MEETING, meeting.getName(), meeting.getActStartTime(), meeting.getRoomName());
                                            createNewView(homeNewBean);
                                        }
                                    }
                                });
                            }
                        }
                    }
                }
            });
        }
    }

    private void createNewView(HomeNewBean homeNewBean) {
        if (getActivity() != null) {
            if (!getActivity().isFinishing()) {
                String desc = "";
                switch (homeNewBean.getType()) {
                    case COURSE:
                        tvHomeNewTitle.setText("最新课程");
                        desc = "请准时到达并签到。";
                        break;
                    case MEETING:
                        tvHomeNewTitle.setText("最新会议");
                        desc = "参与会议者请准时到达，带上有关资料。";
                        break;
                }
                llTopNew.setVisibility(View.VISIBLE);
                if (meetingView == null) {
                    meetingView = getLayoutInflater().inflate(R.layout.item_meeting_list, null, false);
                }
                TextView tvTitle = meetingView.findViewById(R.id.tv_title);
                TextView tvDate = meetingView.findViewById(R.id.tv_date);
                TextView tvDesc = meetingView.findViewById(R.id.tv_desc);
                TextView tvAddress = meetingView.findViewById(R.id.tv_address);

                tvTitle.setText(homeNewBean.getTitle());
                tvDate.setText(homeNewBean.getTime());
                tvAddress.setText(homeNewBean.getAddress());
                tvDesc.setText(desc);

                flNewMeeting.removeAllViews();
                flNewMeeting.addView(meetingView);
                flNewMeeting.setTag(homeNewBean);
                flNewMeeting.requestLayout();
            }
        }
    }

    @OnClick({
            R.id.fl_new_meeting,
            R.id.ll_home_course,
            R.id.ll_home_meeting,
            R.id.ll_highly_recommented
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fl_new_meeting:
                if (view.getTag() != null) {
                    HomeNewBean homeNewBean = (HomeNewBean) view.getTag();
                    switch (homeNewBean.getType()) {
                        case COURSE:
                            findCourseById(homeNewBean);
                            break;
                        case MEETING:
                            findMeetingById(homeNewBean);
                            break;
                    }
                }
                break;
            case R.id.ll_home_course:
                if (getActivity() != null) {
                    reqNewCourse();
                    CourseTableActivity.Companion.navigation(getActivity());
                }
                break;
            case R.id.ll_home_meeting:
                if (getActivity() != null) {
                    startActivity(new Intent(getActivity(), MeetingActivity.class));
                }
                break;
            case R.id.ll_highly_recommented:
                if (getActivity() != null) {
                    String coverId = "";
                    if (fileInfos != null && !fileInfos.isEmpty()) {
                        coverId = fileInfos.get(0).getId();
                    }
                    HighlyRecommentedActivity.Companion.navigation(getActivity(),coverId);
                }
                break;
        }
    }

    /**
     * 查询课程数据跳转到详情
     * @param homeNewBean
     */
    private void findCourseById(HomeNewBean homeNewBean) {
        UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            String userId = userInfo.getId();
            long universityId = userInfo.getUniversityId();
            courseByIdCall = courseApi.findCourseById(1,userId,universityId,homeNewBean.getId(),1,1);
            courseByIdCall.enqueue(new ServerCallback<Page<Course>>(getActivity(),"正在查询课程数据...") {
                @Override
                public void onResponse(boolean success, ServerResponse<Page<Course>> response) {
                    if (success) {
                        if (response != null && response.getBody() != null && !response.getBody().getList().isEmpty()) {
                            if (getActivity() != null) {
                                Course course = response.getBody().getList().get(0);
                                if (course!= null) {
                                    Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
                                    intent.putExtra(CourseDetailActivity.EXTRA_COURSE_ENTITY,course);
                                    startActivity(intent);
                                }

                            }
                        }
                    }
                }
            });
        }

    }

    /**
     * 查询会议数据跳转会议
     * @param homeNewBean
     */
    private void findMeetingById(HomeNewBean homeNewBean) {
        findMeetingByIdCall = meetingApi.findMeetingById(String.valueOf(homeNewBean.getId()),1,1);
        findMeetingByIdCall.enqueue(new ServerCallback<Page<Meeting>>(getActivity(),"正在查询会议数据...") {
            @Override
            public void onResponse(boolean success, ServerResponse<Page<Meeting>> response) {
                if (success) {
                    if (response != null && response.getBody() != null && !response.getBody().getList().isEmpty()) {
                        if (getActivity() != null) {
                            Meeting meeting = response.getBody().getList().get(0);
                            Intent intent = new Intent(getActivity(), MeetingDetailActivity.class);
                            intent.putExtra(MeetingDetailActivity.EXTRA_MEETING_ENTITY,meeting);
                            startActivity(intent);
                        }
                    }
                }
            }
        });
    }


    private void setBanner(List<FileInfoWrapper> list) {
        convenientBanner.setPages(new CBViewHolderCreator() {
            @Override
            public Holder createHolder(View itemView) {
                if (getActivity() != null) {
                    bannerAdapter = new BannerAdapter(itemView, list, getActivity());
                }else{
                    bannerAdapter =  new BannerAdapter(itemView,list,null);
                }

                return  bannerAdapter;
            }

            @Override
            public int getLayoutId() {
                return R.layout.banner_layout;
            }
        }, list);



    }



    @Override
    public Toolbar getToolbar() {
        return null;
    }

    @Override
    public void onResume() {
        super.onResume();
        vt1.startAutoScroll();
        vt2.startAutoScroll();
        if (convenientBanner != null) {
            convenientBanner.startTurning();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        vt1.stopAutoScroll();
        vt2.stopAutoScroll();
        if (convenientBanner != null) {
            convenientBanner.stopTurning();
        }
    }

    private void loadBulletin() {
        messagesCall = bulletinApi.messages(1, 10);
        messagesCall.enqueue(new ServerCallback<Page<Bulletin>>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Page<Bulletin>> response) {
                if (success) {
                    bulletinList = response.getBody().getList();
                    final ArrayList<Bulletin> b1 = new ArrayList<>();
                    final ArrayList<Bulletin> b2 = new ArrayList<>();
                    if (bulletinList != null && bulletinList.size() > 0) {
                        for (int i = 0; i < bulletinList.size(); i++) {
                            if (i % 2 == 0){
                                b1.add(bulletinList.get(i));
                            }else{
                                b2.add(bulletinList.get(i));
                            }
                        }
                        setVt(b1, b2);
                    }else{
                        if (llNotice != null) {
                            llNotice.setVisibility(View.GONE);
                        }
                    }
                }
            }
        });
    }

    private void loadSlide() {
        UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            long universityId = userInfo.getUniversityId();
            selectSlideCall = resourceApi.selectSlide(universityId, FileFunctionFlag.HOME_SLIDE);
            selectSlideCall.enqueue(new ServerCallback<List<FileInfo>>() {
                @Override
                public void onResponse(boolean success, ServerResponse<List<FileInfo>> response) {
                    if (success) {
                        if (response == null) return;
                        fileInfos = response.getBody();
                        if (fileInfos !=null && !fileInfos.isEmpty()) {
                            List<FileInfoWrapper> fileInfoWrappers = new ArrayList<>();
                            for (FileInfo fileInfo : fileInfos) {
                                FileInfoWrapper infoWrapper = new FileInfoWrapper();
                                infoWrapper.setId(fileInfo.getId());
                                infoWrapper.setAdView(null);
                                fileInfoWrappers.add(infoWrapper);
                            }
                            if (userInfo.getNativadsStatus() != null && userInfo.getNativadsStatus() == 1) {
                                if (getActivity() != null) {
                                    new AdCallback(getActivity(), view -> {
                                        FileInfoWrapper fileInfoWrapper = new FileInfoWrapper();
                                        fileInfoWrapper.setId(null);
                                        view.setTag("Home_AD");
                                        fileInfoWrapper.setAdView((NativeExpressADView) view);
                                        //fileInfoWrappers.add(fileInfoWrapper);
                                        convenientBanner.notifyDataSetChanged();
                                    });
                                }
                            }
                            setBanner(fileInfoWrappers);
                        }else{
                            convenientBanner.setVisibility(View.GONE);
                        }
                    }
                }
            });
        }
    }

    private void setVt(final ArrayList<Bulletin> b1, final ArrayList<Bulletin> b2) {
        final ArrayList<String> vtStrs1 = new ArrayList<>();
        final ArrayList<String> vtStrs2 = new ArrayList<>();
        for (Bulletin bulletin : b1) {
            vtStrs1.add(bulletin.getInform());
        }
        for (Bulletin bulletin : b2) {
            vtStrs2.add(bulletin.getInform());
        }

        vt1.setTextList(vtStrs1);
        vt2.setTextList(vtStrs2);

        vt1.setOnItemClickListener(new VerticalTextview.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                BulletinActivity.navigation(getActivity());
            }
        });

        vt2.setOnItemClickListener(new VerticalTextview.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                BulletinActivity.navigation(getActivity());
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshBulletinData(BulletinEvent bulletinEvent) {
        loadBulletin();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateCourseData(ReqNewCourseEvent reqNewCourseEvent) {
        reqNewCourse();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (userTodayMeetingList != null) {
            userTodayMeetingList.cancel();
        }
        if (selectSlideCall != null) {
            selectSlideCall.cancel();
        }
        if (messagesCall != null) {
            messagesCall.cancel();
        }
        if (newCourseListCall != null) {
            newCourseListCall.cancel();
        }
        if (courseByIdCall != null) {
            courseByIdCall.cancel();
        }
        if (findMeetingByIdCall != null) {
            findMeetingByIdCall.cancel();
        }

        if (courseSubscribe != null) {
            courseSubscribe.dispose();
        }

        if (meetingSubscribe != null) {
            meetingSubscribe.dispose();
        }

        if (bannerAdapter != null) {
            bannerAdapter.onDestroyView();
        }
    }
}
